package com.msh.starter.common.web.config;

import com.msh.frame.client.interfaces.IClassLoadLog;
import com.msh.starter.common.web.filter.CorsFilter;
import javax.servlet.Filter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;


/**
 * 解决前端跨域问题
 */
@ConditionalOnProperty(name = "msh.starter.web.cors.enable", havingValue = "true")
public class CorsConfig implements IClassLoadLog {

  @Value("${msh.starter.cors.exposedHeaders:}")
  private String exposedHeaders;

  @Bean
  public FilterRegistrationBean crsFilterBean() {
    FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>();
    //设置为自定义的过滤器Filter
    filterRegistrationBean.setFilter(new CorsFilter(exposedHeaders));
    //拦截所有请求
    filterRegistrationBean.addUrlPatterns("/*");
    //优先级为1
    filterRegistrationBean.setOrder(0);
    return filterRegistrationBean;
  }


  @Override
  public String logInfo() {
    return new StringBuilder()
        .append("----执行类 ")
        .append(CorsConfig.class)
        .append("\r\n")
        .append("--------加载类 ")
        .append(CorsConfig.class)
        .append("\r\n")
        .append("------------参数 ")
        .append("msh.starter.cors.exposedHeaders: ")
        .append(exposedHeaders)
        .append("\r\n")
        .toString();
  }
}
